<template>
  <page-wrap
    :show-top="true"
    :customWrapStyle="customWrapStyle"
    :title="name"
    back
    hideTab
    :hideSafeArea="true"
    txtColor="#222"
    bgColor="transparent"
    class="pageWrap"
  >
    <view
      class="article"
      :style="'padding-top:' + navHeight + 'px;'"
      type="line"
    >
      <view class="search">
        <!-- :search-icon="searchIcon" -->
        <u-search
          :placeholder="showTypePole ? '搜索该职业标杆' : '搜索该职业报告'"
          placeholder-color="#b2b2b2"
          class="library-u-search"
          v-model="keyword"
          height="80"
          bg-color="#ffffff"
          :search-icon="searchIcon"
          :show-action="showRightSearchText"
          @search="handleSearch"
          @custom="handleSearch"
          @blur="closeSearchText"
          @focus="showSearchText"
          maxlength="20"
        ></u-search>
      </view>
      <scroll-view
        class="article-list"
        :scroll-top="scrollTop"
        scroll-y
        :scroll-anchoring="false"
        refresher-enabled
        :refresher-triggered="triggered"
        @refresherrefresh="onRefresh"
        @refresherrestore="onRestore"
        @scrolltolower="loadMore"
        lower-threshold="100"
      >
        <view
          class="father"
          v-for="(item, index) in dataList"
          :key="index"
          @click="handleToDetail(item)"
        >
          <view
            class="left"
            :style="{ backgroundImage: 'url(' + item.bannerUrl + ')' }"
          ></view>
          <view class="right">
            <view class="title">{{ item.activityName }}</view>
            <view class="desc">{{ item.activityIntroduce }}</view>
            <view class="tips">
              <span
                v-for="(tip, index) in getSplitTag(item.activityTags)"
                :key="index"
                >{{ tip }}</span
              >
            </view>
            <view v-if="false" class="number">
              <img :src="viewSrc" />
              <text>{{ kFormatter(item.activityViewNum) }}</text>
            </view>
          </view>
        </view>
        <u-loadmore
          v-if="dataList.length || !loaded"
          class="list-more"
          :status="moreLoading"
          :load-text="loadText"
        />
        <Empty
          v-if="loaded && !dataList.length"
          :baseImg="emptyImg"
          :text="showTypePole ? '暂无相关标杆' : '暂无相关报告'"
          textColor="#888"
          :fontWeight="400"
        />
      </scroll-view>
    </view>
  </page-wrap>
</template>

<script>
import Empty from "@/components/Empty.vue";
import { getSearchJobCase } from "@/api/modules/career";
import ShareMixin from "@/mixins/share";
import ReportShareMixin from "@/mixins/reportShare";

import CryptoJS from "crypto-js";
export default {
  mixins: [ShareMixin, ReportShareMixin],
  components: {
    Empty,
  },
  data() {
    return {
      navHeight: 0,
      personId: uni.getStorageSync("person-id").slice(2) || "",
      searchIcon: this.$imgBaseSelf + "common/search_gray.png",
      scrollTop: 0,
      showRightSearchText: false,
      name: "",
      options: {},
      dataList: [],
      loaded: false,
      triggered: false,
      _triggered: false,
      emptyImg: this.$imgBaseSelf + "common/empty.png",
      keyword: "",
      moreLoading: "loadmore",
      pageParams: {
        pageNo: 1,
        pageSize: 20,
        finished: false,
        loading: false,
      },
      loadText: {
        loadmore: "加载更多",
        loading: "加载中",
        nomore: "已经到底啦",
      },
      isCollect: false,
      showTypePole: true,
    };
  },

  created() {
    this.navHeight = getApp().globalData.navHeight;
  },
  onLoad(opt) {
    this.options = opt;
    this.positionId = opt.positionId;
    this.showTypePole = this.options.showType == "pole";
    this.name = this.options.name + (this.showTypePole ? "·标杆" : "·报告");
    this.shareTitle = this.name;
    this.isCollect = this.options.isCollect;
    this.shareQuery = `positionId=${this.options.positionId}&name=${this.options.name}&layerId=${this.options.layerId}&showType=${this.options.showType}`
    this.sharePath = `/pagesSub/career/moreJobCase/index?${this.shareQuery}`;
    this.shareContent.contentType = (this.options.showType == "pole"?'11':'21')
  },
  mounted() {
    this.getData();
  },
  onShow() {
    console.log("pagesSub/career/moreJobCase/index onShow");

    this.pageParams.pageNo = 1;
    this.moreLoading = "loadmore";
    this.getData();
  },
  computed: {
    formattedDate: function () {
      var today = new Date(); //获取当前时间
      var month = (today.getMonth() + 1).toString().padStart(2, "0"); //获取月份，不足两位的前面补0
      var year = today.getFullYear().toString().substr(0); //获取年份的后两位
      var day = today.getDate().toString().padStart(2, "0"); //获取天数，不足两位的前面补0
      return `${year}-${month}-${day}`; //拼接成mm-yy-dd的格式
    },
  },
  methods: {
    showSearchText() {
      this.showRightSearchText = true;
    },
    closeSearchText() {
      this.showRightSearchText = false;
    },
    getData(isMore) {
      if (this.moreLoading == "loading" || this.moreLoading == "nomore") return;
      const params = {
        pageNo: this.pageParams.pageNo,
        pageSize: this.pageParams.pageSize,
        keyWord: this.keyword,
        personId: this.personId,
        positionId: this.options.positionId, //this.options.positionId
        layerId: this.options.layerId, //this.options.layerId
        dataType: this.showTypePole ? "20" : "10",
      };
      this.moreLoading = "loading";
      getSearchJobCase(params)
        .then((res) => {
          this.pageParams.loading = false;
          this.moreLoading = "loadmore";
          this.loaded = true;
          if (res && res.code == 200) {
            if (isMore) {
              console.log("IsMore res.data", res.data);

              res.data.forEach((item) => {
                item.fakeActivityViewNum = item.activityViewNum;
                // item.activityTypeCode = item.mpaActivityId;
                this.dataList.push(item);
              });
            } else {
              this.dataList = res.data.map((item) => {
                item.fakeActivityViewNum = item.activityViewNum;
                // item.activityTypeCode = item.mpaActivityId;
                return item;
              });
            }

            if (this.pageParams.pageNo >= res.pageparam.pages) {
              this.moreLoading = "nomore";
            }
            console.log("this.pageParams", this.pageParams);
            console.log("this.pageParams.pageNo", this.pageParams.pageNo);
            console.log("this.pageParams.pages", this.pageParams.pages);

            this.pageParams.pageNo++;
          } else {
            this.moreLoading = "nomore";
            uni.showToast({
              title: res.status_desc,
              icon: "none",
              duration: 2000
            });
          }
        })
        .finally(() => {
          this.triggered = false;
          this._triggered = false;
          this.loaded = true;
        });
    },
    kFormatter(num) {
      if (num >= 10000 && num < 1000000) {
        return (num / 1000).toFixed(1) + "K";
      } else if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + "M";
      }
      return num;
    },
    getSplitTag(tags) {
      if (!tags) return;
      return tags.split(",");
    },
    handleSearch() {
      this.onRefresh();
    },
    loadMore() {
      this.getData(true);
    },
    onRestore() {
      this.triggered = false;
      this._triggered = false;
    },
    onRefresh() {
      if (this.scrollTop == 0) {
        this.scrollTop = 0.1;
      } else {
        this.scrollTop = 0;
      }
      console.log("xxxxxx 刷新了 ！！！！！xxxxxxx------->");
      if (this._triggered) return;
      this._triggered = true;

      if (!this.triggered) {
        this.triggered = true;
      }
      this.loaded = false;
      this.moreLoading = "loadmore";
      this.pageParams.pageNo = 1;
      this.getData();
    },
    encrypt(word, keyStr) {
      // word, keyStr第一个参数是加密的字段名字  第二个是key值（16位）
      keyStr = keyStr || "*%&^%$&*()347845"; // 密文（密钥）
      var key = CryptoJS.enc.Utf8.parse(keyStr);
      var srcs = CryptoJS.enc.Utf8.parse(word);
      var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      });
      return encrypted.toString();
    },
    handleToDetail(item) {
      let url =
        "/pagesSub/companyCenter/case/detail?id=" +
        item.mpaActivityId +
        "&&positionId=" +
        this.options.positionId +
        "&&isFromZhishenji=" +
        1 +
        "&&isGetCollect=" +
        1 + 
        "&&showType=" +
        this.options.showType;

      if (item.isBuy == 1) {
        //如果是1那就要传sourceFrom,2则不需要
        url +=
          "&&sourceFrom=" + this.encrypt("zhishenji" + this.formattedDate, "");
      }

      uni.navigateTo({
        url,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.article {
  background-image: url($img-base + "career/jobList_bg.png");
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  .search {
    display: flex;
    padding: 12rpx 32rpx 32rpx 32rpx;
    border-radius: 18px;
    ::v-deep.u-content {
      padding: 0 20rpx 0rpx 32rpx;
    }
    ::v-deep.u-close-wrap {
      transform: scale(1.5);
    }

    ::v-deep.u-icon__img {
      width: 80rpx;
      height: 80rpx;
    }

    .library-u-search {
      flex: 1;
      width: 686rpx;
      height: 72rpx;
    }
  }

  &-list {
    height: calc(100vh - 180px);
    background-color: transparent;
    margin: auto;
    border-radius: 8px;
    box-sizing: border-box;
    flex-grow: 1;
  }
}
.father {
  display: flex;
  padding: 24rpx;
  margin: 15rpx 32rpx 16rpx;
  background: #ffffff;
  border-radius: 16rpx;
  width: calc(100vw - 64rpx);

  .left {
    width: 154rpx;
    height: 168rpx;
    border-radius: 8rpx;
    background-size: cover;
    background-position: center center;
    background-repeat: no-repeat;
  }

  .right {
    margin-left: 36rpx;
    flex: 1;
    min-width: 0;

    .title {
      font-weight: bold;
      color: #222222;
      font-size: 32rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .desc {
      color: rgba(0, 0, 0, 0.5);
      font-size: 26rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-top: 14rpx;
    }

    .tips {
      display: flex;
      margin-top: 14rpx;

      span {
        margin-right: 16rpx;
        font-size: 20rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #555555;
        background: #f5f5f5;
        padding: 6rpx 12rpx;
        border-radius: 4rpx;
      }
    }

    .number {
      display: flex;
      align-items: center;
      margin-top: 20rpx;

      img {
        width: 32rpx;
        height: 24rpx;
        margin-right: 16rpx;
      }

      text {
        font-size: 24rpx;
        color: #bfbfbf;
      }
    }
  }
}
</style>
